﻿#pragma execution_character_set("utf-8")
// 本文件为utf-8 编码格式

#include "GDUtil.h"
#include <stdio.h>
#include <iostream>
#include <typeinfo>
#include <CrossAppExt.h>

#include "../C2DXShareSDK/C2DXShareSDK.h"

#include "RootWindow.h"

#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
#include <dirent.h>
#endif

#include "../Views/GDAlertView.h"
#include "../Views/GDTaskView.h"
#include "../CartoonHouse.h"
#include "../Views/GDShareView.h"

//#ifndef WIN32

//#define stricmp _px
//#endif

using namespace cn::sharesdk;

GDUtil::GDUtil(void)
{
}


GDUtil::~GDUtil(void)
{
}

time_t lastTouchTime = time(NULL);

bool isValidTouch()
{
	time_t now = time(NULL);
	if (now - lastTouchTime < 1){
		return false;
	}
	else{
		lastTouchTime = now;
	}
	return true;
}

void GDUtil::setViewFollow(CAView *view1, CAView *view2){
	if (view1 == NULL || view2 == NULL){
		return;
	}
	CCRect rect = view2->getFrame();
	rect.origin.y = view1->getFrameOrigin().y + view1->getBounds().size.height;
	view2->setFrame(rect);
}

void GDUtil::setViewsFollow(int count, ...){
	if (count <= 0) return ;

	va_list argptr;

	va_start(argptr, count);

	CAView *first,*next;

	for (int i = 0; i < count; i++){
		if (i == 0){ // 如果是第一个参数
			first = va_arg(argptr, CAView*);
		}
		else{
			next = va_arg(argptr, CAView*);
			setViewFollow(first,next);
			first = next;
		}
	}

	va_end(argptr);
}

void GDUtil::setViewFollowHorizontal(CAView *view1, CAView *view2){
	CCRect rect = view2->getFrame();
	rect.origin.x = view1->getFrameOrigin().x + view1->getBounds().size.width;
	//rect.origin.y = view1->getFrameOrigin().y;
	view2->setFrame(rect);
}

void GDUtil::setViewsFollowHorizontal(int count, ...){
	if (count <= 0) return;

	va_list argptr;

	va_start(argptr, count);

	CAView *first, *next;

	for (int i = 0; i < count; i++){
		if (i == 0){ // 如果是第一个参数
			first = va_arg(argptr, CAView*);
		}
		else{
			next = va_arg(argptr, CAView*);
			setViewFollowHorizontal(first, next);
			first = next;
		}
	}

	va_end(argptr);
}

void GDUtil::setViewFollowStep(int step, CAView *view1, CAView *view2){
	CCRect rect = view2->getFrame();
	rect.origin.y = view1->getFrameOrigin().y + view1->getBounds().size.height + step;
	// CCLog("设置view竖向跟随，view1=[%f,%f],view2=[%f,%f]", view1->getFrameOrigin().x, view1->getFrameOrigin().y, view2->getFrameOrigin().x, view2->getFrameOrigin().y);
	view2->setFrame(rect);
}
void GDUtil::setViewsFollowStep(int step, int count, ...){
	if (count <= 0) return;

	va_list argptr;

	va_start(argptr, count);

	CAView *first, *next;

	for (int i = 0; i < count; i++){
		if (i == 0){ // 如果是第一个参数
			first = va_arg(argptr, CAView*);
		}
		else{
			next = va_arg(argptr, CAView*);
			setViewFollowStep(step, first, next);
			first = next;
		}
	}

	va_end(argptr);
}
void GDUtil::setViewFollowHorizontalStep(int step, CAView *view1, CAView *view2){
	CCRect rect = view2->getFrame();
	rect.origin.x = view1->getFrameOrigin().x + view1->getBounds().size.width + step;
	//rect.origin.y = view1->getFrameOrigin().y;
	view2->setFrame(rect);
}
void GDUtil::setViewsFollowHorizontalStep(int step, int count, ...){
	if (count <= 0) return;

	va_list argptr;

	va_start(argptr, count);

	CAView *first, *next;

	for (int i = 0; i < count; i++){
		if (i == 0){ // 如果是第一个参数
			first = va_arg(argptr, CAView*);
		}
		else{
			next = va_arg(argptr, CAView*);
			setViewFollowHorizontalStep(step,first, next);
			first = next;
		}
	}

	va_end(argptr);
}

void GDUtil::setViewHeight(CAView *view, float height){
	CCRect rect = view->getFrame();
	rect.size.height = height;
	view->setFrame(rect);
}

void GDUtil::setViewHeight(CAView *view, int height){
	CCRect rect = view->getFrame();
	rect.size.height = height;
	view->setFrame(rect);
}

void GDUtil::setViewHeight(CAView *view, CAView *footView, int space){
	CCRect rect = view->getFrame();
	rect.size.height = footView->getFrameOrigin().y + footView->getBounds().size.height + space;
	view->setFrame(rect);
}

void GDUtil::setViewHeightFull(CAView *view){
	int height = GDUtil::getViewInnerHeight(view);
	GDUtil::setViewHeight(view, height);
}

int GDUtil::getViewHeight(CAView *view){
	return view->getFrameOrigin().y + view->getBounds().size.height;
}

int GDUtil::getViewInnerHeight(CAView *view){
	int height = 0;

	CAVector<CAView*> subViews = view->getSubviews();
	if (subViews.empty()){
		return height;
	}
	int subCount = (int)subViews.size();
	if (subCount == 0){
		return height;
	}

	CAView *lastSubView = subViews.at(subCount-1);
	return GDUtil::getViewHeight(lastSubView);
}

void GDUtil::setViewWidth(CAView *view, int width){
	CCRect rect = view->getFrame();
	rect.size.width = width;
	view->setFrame(rect);
}

void GDUtil::setViewWidth(CAView *view, float width){
	CCRect rect = view->getFrame();
	rect.size.width = width;
	view->setFrame(rect);
}

void GDUtil::setViewWidth(CAView *view, CAView *subView){
	CCRect rect = view->getFrame();
	rect.size.width = subView->getFrameOrigin().x + subView->getBounds().size.width;
	view->setFrame(rect);
}

void GDUtil::subViewVerticalSort(CAView *view, int step){
	//int height = 0;

	CAVector<CAView*> subViews = view->getSubviews();
	if (subViews.empty()){
		return;
	}

	int count = (int)subViews.size();

	if (count == 0){
		return ;
	}

	CAView *first;
	CAView *subView;

	for (int i = 0; i < count; i++){
		if (i == 0){
			first = subViews.at(i);
			first->setFrameOrigin(CCPoint(0, 0));
		}
		else{
			subView = subViews.at(i);
			GDUtil::setViewFollowStep(step,first, subView);
			first = subView;
		}
	}
}

void GDUtil::subViewHorizontalSort(CAView *view, int step){
	//int height = 0;

	CAVector<CAView*> subViews = view->getSubviews();
	if (subViews.empty()){
		return;
	}

	int count = (int)subViews.size();

	if (count == 0){
		return;
	}

	CAView *first;
	CAView *subView;

	for (int i = 0; i < count; i++){
		if (i == 0){
			first = subViews.at(i);
			first->setFrameOrigin(CCPoint(0, 0));
		}
		else{
			subView = subViews.at(i);
			GDUtil::setViewFollowHorizontalStep(step, first, subView);
			first = subView;
		}
	}
}

unsigned int GDUtil::getScaleHeight(CCSize size, int width){
	return width * size.height / size.width;
}

unsigned int GDUtil::getImageScaleHeight(CAImage *image, int width){
	CCSize size = image->getContentSize();
	return width * size.height / size.width;
}

void GDUtil::setSubViewToCenter(CAView *superView, CAView *subView){
	CCSize superSize = superView->getBounds().size;
	CCRect subRect = subView->getFrame();

	subRect.origin.x = superSize.width / 2;
	subRect.origin.y = superSize.height / 2;
	subView->setCenter(subRect);
}

void GDUtil::setSubViewToHorizontalCenter(CAView *superView, CAView *subView){
	CCSize superSize = superView->getBounds().size;
	CCRect subRect = subView->getFrame();

	subRect.origin.x = (superSize.width - subRect.size.width) / 2;
	subView->setFrame(subRect);
}
void GDUtil::setSubViewToVerticalCenter(CAView *superView, CAView *subView) // 设置 subView 在 superView 垂直居中
{
	CCSize superSize = superView->getBounds().size;
	CCRect subRect = subView->getFrame();

	subRect.origin.y = (superSize.height - subRect.size.height) / 2;
	subView->setFrame(subRect);
}

CAView* GDUtil::getLastSubView(CAView *view){
	if (view == NULL){
		return NULL;
	}

	int count = view->getSubviewsCount();

	if (count == 0){
		return NULL;
	}

	return view->getSubviews().at(count - 1);
}

int GDUtil::getMaxZOrderInSubView(CAView *view){
	//CCLog("%s",__FUNCTION__);
	int order = 0;
	int suborder = 0;
	if (view->getZOrder() > order){
		order = view->getZOrder();
	}

	int count = view->getSubviewsCount();

	if (count>0){ // 有子元素
		CAVector<CAView*> subviews = view->getSubviews();
		for (int i = 0; i < count; i++){
			suborder = GDUtil::getMaxZOrderInSubView(subviews.at(i));
			if (suborder>order){
				order = suborder;
			}
		}
	}

	return order;
}

void GDUtil::removeSubView(CAView *rootView, std::string exceptTextTag)
{
	CAVector<CAView*> subviews = rootView->getSubviews();
	int subViewCount = subviews.size();
	CAView *view = NULL;
	for (int i = 0; i < subViewCount; i++){
		view = subviews.at(i);
		if (exceptTextTag == view->getTextTag()){
			continue;
		}
		rootView->removeSubview(view);
	}
}

void GDUtil::removeSubViewExceptZorder(CAView *view, int zorder)
{
	// 删除子元素
	CAVector<CAView*> subviews = view->getSubviews();
	CAVector<CAView*>::iterator itr;
	for (itr = subviews.begin(); itr != subviews.end(); itr++)
	{
		if ((*itr)->getZOrder() != zorder){
			(*itr)->removeFromSuperview();
		}
	}
}

void GDUtil::pushViewControllerToNavigationController(CANavigationController* navigationController, CAViewController *viewController, bool animated, bool needInit)
{
	if (RootWindow::getInstance()->getDrawerController()->isShowLeftViewController())
	{
		RootWindow::getInstance()->getDrawerController()->hideLeftViewController(false);
	}
	if (needInit){
		viewController->init();
		viewController->autorelease();
	}

	if (navigationController == NULL){
		navigationController = RootWindow::getInstance()->getRootNavigationController();
	}

	navigationController->pushViewController(viewController, animated);

    //需要修改引擎
    long wCount = navigationController->getViewControllerCount();
    //CCLog("------打开窗口数量：%d------",(int)wCount);
    if(wCount > 4){
		navigationController->popViewControllerAtIndex(1);
        //CCLog("---del---打开窗口数量：%d------",RootWindow::getInstance()->getRootNavigationController()->getViewControllerCount());
    }	
}

void GDUtil::pushViewController(CAViewController *viewController, bool animated,bool needInit){
	GDUtil::pushViewControllerToNavigationController(NULL, viewController, animated, needInit);
}

void GDUtil::pushViewController(CANavigationController* navigationController, CAViewController *viewController){
	GDUtil::pushViewControllerToNavigationController(navigationController, viewController, true, true);
}


void GDUtil::presentModalViewController(CAWindow *window, CAViewController *viewController, bool animated, const std::string& navigationBarBackGroundImage, bool isHiddenNavigationBar){
	CANavigationController *loginNController = new CANavigationController();
	loginNController->autorelease();
	loginNController->setNavigationBarBackGroundImage(CAImage::create(navigationBackgroundWhite));
	loginNController->initWithRootViewController(viewController);
	loginNController->setNavigationBarHidden(isHiddenNavigationBar, false);
	//viewController->init();
	viewController->autorelease();
	window->presentModalViewController(loginNController, animated);
}



void GDUtil::closeViewController(CAViewController *viewController, bool animated){
	// 优先处理 parsent view
	RootWindow *window = RootWindow::getInstance();
    
    //animated = false;
    
	if (GD_SHARE_VIEW && GD_SHARE_VIEW->isVisible()){
		GD_SHARE_VIEW->setVisible(false);
		return;
	}

	if (window->getModalViewController())
	{
		CANavigationController *controller = (CANavigationController*)window->getModalViewController();

		if (controller && controller->getViewControllerCount() > 1){
			viewController = controller->getViewControllerAtIndex(controller->getViewControllerCount() - 1);
			
			controller->popViewControllerAnimated(true);
			return;
		}
		window->dismissModalViewController(animated);
		return;
	}

	CANavigationController *navController = NULL;
	if (viewController){		
		navController = viewController->getNavigationController();
	}

	if (navController == NULL){
		RootWindow *window = RootWindow::getInstance();
		navController = window->getRootNavigationController();
	}

	if (navController != NULL && navController->getViewControllerCount()>1){
		viewController = navController->getViewControllerAtIndex(navController->getViewControllerCount() - 1);
		
		navController->popViewControllerAnimated(animated);
		return;
	}

	else if (window->getDrawerController()->isShowLeftViewController())
	{
		window->getDrawerController()->hideLeftViewController(animated);
	}
	else{
		window->showExitAlertView();
	}
}

void GDUtil::closeToRootViewController(CAViewController *viewController, bool animated){
	CANavigationController *navController = NULL;
	if (viewController){
		navController = viewController->getNavigationController();		
	}

	if (navController == NULL){
		RootWindow *window = RootWindow::getInstance();
		navController = window->getRootNavigationController();
	}

	if (navController != NULL){
		navController->popToRootViewControllerAnimated(animated);
	}

	RootWindow *window = RootWindow::getInstance();

	if (window->getModalViewController())
	{
		window->dismissModalViewController(animated);
	}
}

void GDUtil::task(const char* msg)
{
	GDTaskView::showTask(msg);
}

void GDUtil::alert(const char* msg){
	GDAlertView *alertView = GDAlertView::createWithText("提示", msg, "确定", NULL);
	alertView->setZOrder(100);
	alertView->setTarget(RootWindow::getInstance(), CAAlertView_selector(RootWindow::onAlertView));
	keyBackEnable = false;
	alertView->show();
}

void GDUtil::alertDelay(const char* msg, float delay)
{
	GDAlertView *alertView = GDAlertView::createWithText("提示", msg, "确定", NULL);
	alertView->setZOrder(100);
	alertView->setTarget(RootWindow::getInstance(), CAAlertView_selector(RootWindow::onAlertView));
	keyBackEnable = false;
	alertView->delayShow(delay);
}

void GDUtil::alert(const char* msg, CAObject* target, SEL_CAAlertBtnEvent selector){
	GDAlertView *alertView = GDAlertView::createWithText("提示", msg, "确定", NULL);
	alertView->setZOrder(100);
	alertView->setTarget(target, selector);
	alertView->show();
}

void GDUtil::confirm(const char* msg, CAObject* target, SEL_CAAlertBtnEvent selector, const char* title, const char* ok, const char* cancel){
	GDAlertView* alertView = GDAlertView::createWithText(title, msg, cancel, ok, NULL);
	alertView->setZOrder(100);
	alertView->setTarget(target, selector);
	alertView->show();
}

int GDUtil::stringToInt(std::string str){
	if (str.empty() || str == ""){
		return 0;
	}

	return atoi(str.c_str());
}

std::string GDUtil::intToString(int i){
	return CCString::createWithFormat("%d", i)->m_sString;
}

std::string GDUtil::stringAdd(string str, int add){
	return intToString(stringToInt(str) + add);
}

void GDUtil::shareResultHandler(C2DXResponseState state, C2DXPlatType platType, CCDictionary *shareInfo, CCDictionary *error)
{
   
    if(error &&  error->objectForKey("error_msg")){
        CCString *error_info = (CCString*)error->objectForKey("error_msg");
		GDUtil::task(error_info->getCString());
        return;
    }
	
	switch (state) {
	case C2DXResponseStateSuccess:
	{
		//CCLog("分享成功");
		GDUtil::sendStatisticsToService("1004", GD_SHARE_VIEW->getGoodsId(), GDUtil::intToString((int)platType));
		//if (platType == C2DXPlatTypeWeixiTimeline){
		GDUtil::task("分享成功");
		//}
	}
		
		break;
	case C2DXResponseStateFail:
		//CCLog("分享失败");
		//if (platType == C2DXPlatTypeWeixiTimeline){
		GDUtil::task("分享失败");
		//}
		break;
	default:
           
		break;
	}
	GD_SHARE_VIEW->setGoodsId(""); // 清空goodsid
}

void GDUtil::share(cn::sharesdk::C2DXPlatType platType, std::string title, const std::string cnt, const std::string description, const std::string url, const std::string imageUrl, const std::string goodsId)
{
	std::string plantformId = GDUtil::intToString((int)platType);
	GDUtil::share(plantformId, title, cnt, description, url, imageUrl, goodsId);
}

void GDUtil::share(std::string plantformId, std::string title, const std::string cnt, const std::string description, const std::string urls, const std::string imageUrl, const std::string goodsId){
	std::string url = urls;
	std::string parse = "";
	if (plantformId != "1"){
		if (url.find("?") != url.npos){
			parse = "&";
		}
		else{
			parse = "?";
		}
		parse = parse + "pid=" + plantformId  + "&is_share=1&wxdpy=1";
	}
	url = url + parse;
	if(IS_DEBUG) CCLog("分享到微信，标题:%s,内容：%s,描述：%s,图片地址：%s,url:%s", title.c_str(), cnt.c_str(), description.c_str(), imageUrl.c_str(), url.c_str());
	
	CCDictionary *content = CCDictionary::create();
	content->setObject(CCString::create(cnt), "content");
	content->setObject(CCString::create(title), "title");
	content->setObject(CCString::create(description), "description");
	//content->setObject(CCString::create("内容"), "content");
	//content->setObject(CCString::create("标题"), "title");
	//content->setObject(CCString::create("描述"), "description");
	content->setObject(CCString::create(imageUrl), "image");
	content->setObject(CCString::create(url), "url");
	content->setObject(CCString::createWithFormat("%d", C2DXContentTypeNews), "type");
	
	content->setObject(CCString::create("extInfo"), "extInfo");

	C2DXPlatType plant = (C2DXPlatType)atoi(plantformId.c_str());

	switch (plant)
	{
	case cn::sharesdk::C2DXPlatTypeSinaWeibo:
	{
		content->setObject(CCString::create(cnt + "，" + title + "。链接地址：" + url), "content");
		break;
	}
		
	case cn::sharesdk::C2DXPlatTypeWeixiSession:
		break;
	case cn::sharesdk::C2DXPlatTypeWeixiTimeline:
		break;
	case cn::sharesdk::C2DXPlatTypeQQ:
		break;
	case cn::sharesdk::C2DXPlatTypeWeixiFav:
		break;
	default:
		break;
	}

	if (GD_SHARE_VIEW == NULL){
		CAView *rootWindow = CAApplication::getApplication()->getRootWindow();
		GD_SHARE_VIEW = GDShareView::createWithFrame(CCRect(0, 0, rootWindow->getBounds().size.width, rootWindow->getBounds().size.height));
		GD_SHARE_VIEW->setZOrder(10);
		rootWindow->addSubview(GD_SHARE_VIEW);
		GD_SHARE_VIEW->setVisible(false);
	}

	if (!goodsId.empty()){
		GD_SHARE_VIEW->setGoodsId(goodsId);
	}
	GDUtil::sendStatisticsToService("1003", GD_SHARE_VIEW->getGoodsId(), plantformId);
	
	C2DXShareSDK::showShareView(plant, content, GDUtil::shareResultHandler);
}

void GDUtil::showGDShareView(const std::string title, const std::string cnt, const std::string description, const std::string url, const std::string imageUrl, const std::string goodsId,map<int, string> titleMap, map<int, string> cntMap){
	if (GD_SHARE_VIEW == NULL){
		CAView *rootWindow = CAApplication::getApplication()->getRootWindow();
		GD_SHARE_VIEW = GDShareView::createWithFrame(CCRect(0, 0, rootWindow->getBounds().size.width, rootWindow->getBounds().size.height));
		GD_SHARE_VIEW->setZOrder(10);
		rootWindow->addSubview(GD_SHARE_VIEW);
	}

	GD_SHARE_VIEW->setShareInfo(title, cnt, description, url, imageUrl, goodsId, titleMap, cntMap);
	GD_SHARE_VIEW->setVisible(true);
}

void GDUtil::thirdOuthResultHandler(C2DXResponseState state, C2DXPlatType platType, CCDictionary *error){
    
    if(error &&  error->objectForKey("error_msg")){
        CCString *error_info = (CCString*)error->objectForKey("error_msg");
		GDUtil::task(error_info->getCString());
        return;
    }
    
	switch (state) {
	case C2DXResponseStateSuccess:
		if (IS_DEBUG) CCLog("授权成功");
		C2DXShareSDK::getUserInfo(platType, getThirdUserResultHandler);
		break;
	case C2DXResponseStateFail:
		if (IS_DEBUG) CCLog("授权失败");
		GDUtil::task("授权失败,请重试");
		break;
	default:
		break;
	}
}

void GDUtil::getThirdUserResultHandler(C2DXResponseState state, C2DXPlatType platType, CCDictionary *userInfo, CCDictionary *error){
	if (state == C2DXResponseStateSuccess) // 获取成功
	{
		//std::string imagePath = CCFileUtils::sharedFileUtils()->getWritablePath() + "getThirdUserResultHandler.xml";
		//userInfo->writeToFile(imagePath.c_str());

		std::map<string, string> mm;
		mm["type"] = CCString::createWithFormat("%d", (int)platType)->m_sString;
		// username【用户名】, pic【头像】, sex【性别】, openid【平台ID】, type【平台类型】

		switch (platType){
        case C2DXPlatTypeQZone:
		case C2DXPlatTypeQQ:{
			mm["sex"] = userInfo->valueForKey("gender")->m_sString; // dynamic_cast<CCString *>(userInfo->objectForKey("gender"))->getCString(); // 性别
			mm["username"] = userInfo->valueForKey("nickname")->m_sString; // dynamic_cast<CCString *>(userInfo->objectForKey("nickname"))->getCString(); // 昵称
			
			std::string headUrl = userInfo->valueForKey("figureurl")->m_sString; //dynamic_cast<CCString *>(userInfo->objectForKey("figureurl"))->getCString();
			const char* url = headUrl.c_str();
			string openId(strstr(url + strlen("http://qzapp.qlogo.cn/qzapp/"), "/") + 1);
			mm["openid"] = openId.substr(0, 32);
			mm["pic"] = userInfo->valueForKey("figureurl_qq_2")->m_sString; // dynamic_cast<CCString *>(userInfo->objectForKey("figureurl_qq_2"))->getCString(); // 头像

			break;
		}
		case C2DXPlatTypeSinaWeibo:{
			CCDictionary *status = dynamic_cast<CCDictionary *>(userInfo->objectForKey("status"));
			if (status){
				mm["openid"] = status->valueForKey("idstr")->m_sString; //dynamic_cast<CCString *>(userInfo->objectForKey("nickname"))->getCString(); // id
			}
			mm["sex"] = userInfo->valueForKey("gender")->m_sString; // 性别
			mm["username"] = userInfo->valueForKey("name")->m_sString; //dynamic_cast<CCString *>(userInfo->objectForKey("name"))->getCString(); // 昵称
			
			mm["pic"] = userInfo->valueForKey("avatar_large")->m_sString; //dynamic_cast<CCString *>(userInfo->objectForKey("avatar_large"))->getCString(); // 头像
			break;
		}
		case C2DXPlatTypeWeixiSession:
		case C2DXPlatTypeWeixiTimeline:
		case C2DXPlatTypeWeixiFav:{
			mm["openid"] = userInfo->valueForKey("openid")->m_sString; //dynamic_cast<CCString *>(userInfo->objectForKey("nickname"))->getCString(); // id			
			mm["sex"] = userInfo->valueForKey("sex")->m_sString; // 性别
			mm["username"] = userInfo->valueForKey("nickname")->m_sString; //dynamic_cast<CCString *>(userInfo->objectForKey("name"))->getCString(); // 昵称
			mm["pic"] = userInfo->valueForKey("headimgurl")->m_sString; //dynamic_cast<CCString *>(userInfo->objectForKey("avatar_large"))->getCString(); // 头像
			break;
		}
		}
		
		//GDHttpUtil::getInstance()->send_post(GDThirdLoginUrl, mm, LoginController::getInstance(false), CommonHttpJson_selector(LoginController::thirdLoginResultHandler));
	}
	else{
		GDUtil::task("获取信息失败,请重试");
	}
}

void GDUtil::stringTimeToTm(struct tm& tm_, std::string stringTime,const std::string format){
	if (stringTime.empty() || stringTime == "" || stringTime == "0"){
		return ;
	}

	int year = 0, month = 0, day = 0;
	sscanf(stringTime.c_str(), format.c_str(), &year, &month, &day);
	// CCLog("--出生日期：%s,转换后%d年%d月%d日", stringTime.c_str(), year, month, day);
	tm_.tm_year = year-1900;
	tm_.tm_mon = month - 1;
	tm_.tm_mday = day;
}

std::string GDUtil::tmToStringTime(struct tm &tm, const char* format, std::string defaultStr){
	if (tm.tm_year == 0 && tm.tm_mon == 0 && tm.tm_mday == 0){
		return defaultStr;
	}
	return CCString::createWithFormat(format, tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec)->m_sString;
}

std::string GDUtil::timetToStringTime(time_t &tt, const char* format){
	struct tm *p = localtime(&tt);
	char s[80];
	strftime(s, 80, format, p);
	return s;
}

std::string GDUtil::timeToStringTime(struct tm &tm, const char* format)
{
	struct tm *p = &tm;
	char s[80];
	strftime(s, 80, format, p);
	return s;
}
std::string GDUtil::timeToStringTime(long seconds, const char* format){
	time_t t = time_t(seconds);
	return timetToStringTime(t, format);
}
std::string GDUtil::timeToStringTime(std::string seconds, const char* format)
{
	time_t t = std::atoi(seconds.c_str());
	return timetToStringTime(t, format);
}

std::string GDUtil::parseTime(long seconds, const char* format){
	time_t now = time(NULL);
	time_t t = time_t(seconds);
	
	std::string time = "";

	if (t > now){ // 如果是未来的时间
		time = "刚刚";
		//return timeToStringTime(t, format);
	}
	else{
		double diff = difftime(now, t);
		//CCLog("时间差：%lf", diff);
	
		if (diff < ONE_MINUTE_SEC){ // 如果相差不到1分钟
			time = "刚刚";
		}
		else if (diff < ONE_HOUR_SEC){ // 如果相差不到1小时
			int minute = diff / ONE_MINUTE_SEC;
			time = CCString::createWithFormat("%d分钟前", minute + 1)->m_sString;
		}
		else if (diff < ONE_DAY_SEC){
			int hour = diff / ONE_HOUR_SEC;
			time = CCString::createWithFormat("%d小时前", hour)->m_sString;
		}
		else{
			int day = diff / ONE_DAY_SEC; // 天数
			if (day <= 30){
				time = CCString::createWithFormat("%d天前", day)->m_sString;
			}
			else{
				time = "一月前";
				//return timetToStringTime(t, format);
			}
		}
	}
	return time + format;
}

std::string GDUtil::parseTime(std::string seconds, const char* format){
	long time = std::atol(seconds.c_str());
	return parseTime(time, format);
}

std::string GDUtil::formatSecondsToDateTime(std::string seconds,const char *format){
	time_t t = std::atoi(seconds.c_str());
	struct tm *p = localtime(&t);
	char s[80];
	strftime(s, 80, format, p);
	return s;
}

void GDUtil::setShaderRircleImage(CAView *view){
	/**/
	CAGLProgram* pProgram = new CAGLProgram();
	pProgram->initWithVertexShaderFilename("shader/rircleImage.vsh", "shader/rircleImage.fsh");   //载入着色器程序  
	pProgram->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);
	pProgram->addAttribute(kCCAttributeNameColor, kCCVertexAttrib_Color);
	pProgram->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);
	pProgram->link();
	pProgram->updateUniforms();
	GLuint blurSizeLocation = glGetUniformLocation(pProgram->getProgram(), "blurSize");
	GLuint radiusLocation = glGetUniformLocation(pProgram->getProgram(), "radius");
	GLuint centerPointLocation = glGetUniformLocation(pProgram->getProgram(), "centerPoint");
	pProgram->setUniformLocationWith2f(blurSizeLocation, view->getBounds().size.width, view->getBounds().size.height);
	pProgram->setUniformLocationWith1f(radiusLocation, min(view->getBounds().size.width, view->getBounds().size.height) / 2); 
	pProgram->setUniformLocationWith2f(centerPointLocation, view->getBounds().size.width/2, view->getBounds().size.height/2);
	view->setShaderProgram(pProgram);
	pProgram->release();
	
}

void GDUtil::setShaderBlurImage(CAView *view){
	if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID){
		return;
	}

	/**/
	CAGLProgram* pProgram = new CAGLProgram();
	pProgram->initWithVertexShaderFilename("shader/blur.vsh", "shader/blur.fsh");   //载入着色器程序  
	pProgram->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);
	pProgram->addAttribute(kCCAttributeNameColor, kCCVertexAttrib_Color);
	pProgram->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);
	pProgram->link();
	pProgram->updateUniforms();
	GLuint blurLocation = glGetUniformLocation(pProgram->getProgram(), "blurSize");
	pProgram->setUniformLocationWith2f(blurLocation, 1.0 / view->getBounds().size.width, 1.0 / view->getBounds().size.height);
	view->setShaderProgram(pProgram);
	pProgram->release();
	
}


CALabel* GDUtil::createLabel(const char* title, const CAColor4B& col, int fontSize, const char* fontName, const CATextAlignment& textAlignment, const CAVerticalTextAlignment& verticalTextAlignment){
	CALabel *label = new CALabel();
	if (label && label->init())
	{
		label->autorelease();
		label->setText(title);
		label->setColor(col);
		label->setFontSize(fontSize);
		label->setFontName(fontName);
		label->setTextAlignment(textAlignment);
		label->setVerticalTextAlignmet(verticalTextAlignment);
		return label;
	}
    return  NULL;
}

CALabel* GDUtil::createLabelWithFrame(const CCRect& rect, const char* title, const CAColor4B& col, int fontSize, const char* fontName, const CATextAlignment& textAlignment, const CAVerticalTextAlignment& verticalTextAlignment){
	CALabel *label = CALabel::createWithFrame(rect);
	if (label){
		label->setText(title);
		label->setColor(col);
		label->setFontSize(fontSize);
		label->setFontName(fontName);
		label->setTextAlignment(textAlignment);
		label->setVerticalTextAlignmet(verticalTextAlignment);
	}
	return label;
}

CALabel* GDUtil::createLabelWithCenter(const CCRect& rect, const char* title, const CAColor4B& col, int fontSize, const char* fontName, const CATextAlignment& textAlignment, const CAVerticalTextAlignment& verticalTextAlignment){
	CALabel *label = CALabel::createWithCenter(rect);
	if (label){
		label->setText(title);
		label->setColor(col);
		label->setFontSize(fontSize);
		label->setFontName(fontName);
		label->setTextAlignment(textAlignment);
		label->setVerticalTextAlignmet(verticalTextAlignment);
	}
	return label;
}

void GDUtil::setLabelFullWidth(CALabel *label, float maxWidth){
	CCRect rect = label->getFrame();
	float width = CAImage::getStringWidth(label->getFontName().c_str(), label->getFontSize(), label->getText());
	if (maxWidth>0 && width > maxWidth){
		width = maxWidth;
	}
	rect.size.width = width;
	label->setFrame(rect);
}

int GDUtil::getLabelWidth(CALabel *label){
	return CAImage::getStringWidth(label->getFontName().c_str(), label->getFontSize(), label->getText());
}

int GDUtil::getLabelHeight(CALabel *label)
{
	return CAImage::getStringHeight(label->getFontName().c_str(), label->getFontSize(), label->getText(), label->getBounds().size.width, label->getLineSpacing(), false);
}

std::string GDUtil::saveImage(CAImage *image, std::string fileName){
	std::string imagePath = CCFileUtils::sharedFileUtils()->getWritablePath() + "image/";
	CCFileUtils::sharedFileUtils()->createDirectory(imagePath.c_str());

	const std::string imageFile = imagePath + fileName;
	
	image->saveToFile(imageFile);
	
	return imageFile;
}

CAColor4B GDUtil::parseColor(std::string color){
	const char *buf;
	if (color.length() > 6){ // 如果长度大于6
		buf = strdup(color.c_str() + 1);
	}
	else{
		buf = color.c_str();
	}
	
	int r = 0, g = 0, b = 0;

	sscanf(buf, "%2x%2x%2x", &r, &g, &b);
	return ccc4(r,g,b,255);
}

void GDUtil::runFavAction(CAView* view){
	view->runAction(CCSequence::create(CCScaleTo::create(0.1, 1.5), CCScaleTo::create(0, 1.3), CCScaleTo::create(0.2, 1), NULL));
}
std::map<std::string, std::string> GDUtil::parseUrl(const std::string &url){
	std::map<std::string, std::string> key_value;

	int iPos = (int)url.find("?");
	
	if (iPos > 0){
		//CCLog("iPos:%d", iPos);
		std::string queryString = url.substr(iPos + 1, url.length() - iPos - 1);
		//CCLog("querystring:%s", queryString.c_str());

		iPos = (int)queryString.find("&");
		std::string keyValue="";

		while (iPos>0)
		{
			keyValue = queryString.substr(0, iPos);
			int keyValueSplit = (int)keyValue.find("=");
			if (keyValueSplit > 0){
				key_value[keyValue.substr(0, keyValueSplit)] = DecodeURL(keyValue.substr(keyValueSplit + 1, keyValue.length() - keyValueSplit - 1));
			}

			queryString = queryString.substr(iPos + 1, queryString.length() - iPos - 1);
			iPos = (int)queryString.find("&");
		}

		if (queryString.length() > 0){
			keyValue = queryString;
			int keyValueSplit = (int)keyValue.find("=");
			if (keyValueSplit > 0){
				key_value[keyValue.substr(0, keyValueSplit)] = DecodeURL(keyValue.substr(keyValueSplit + 1, keyValue.length() - keyValueSplit - 1));
			}
		}
	}
	
	return key_value;
}

std::string GDUtil::getDiscount(std::string curPrice, std::string oldPrice){
	//if (curPrice == oldPrice){//价格不能用字符串比较
	//	return "";
	//}
	
	double curPricef = atof(curPrice.c_str());
	double oldPricef = atof(oldPrice.c_str());
    
    if(curPricef == oldPricef){
        return "";
    }
	
	double discount = curPricef / oldPricef * 10;

	std::string value = CCString::createWithFormat("%.1f折", discount)->m_sString;
	return value;
}

void GDUtil::jsCallBackFinished(const std::string &message, CAViewController *viewController){
	if(IS_DEBUG) CCLog("jsCallBackFinished %s", message.c_str());
	
}

void GDUtil::replace(std::string &s1, const std::string &s2, const std::string &s3){
	std::string::size_type pos = 0;
	std::string::size_type a = s2.size();
	std::string::size_type b = s3.size();
	while ((pos = s1.find(s2, pos)) != string::npos)
	{
		s1.replace(pos, a, s3);
		pos += b;
	}
}

void GDUtil::trimNull(std::string &s1, bool isDeleteEnter)
{
	if (s1.empty() || s1 == "" || s1.length() < 1){
		return;
	}
	GDUtil::replace(s1, " ", ""); // 替换半角空格
	GDUtil::replace(s1, "　", ""); // 替换全角空格
	GDUtil::replace(s1, "\t", ""); // 替换制表符
	if (isDeleteEnter){
		GDUtil::replace(s1, "\n", "");
		GDUtil::replace(s1, "\r", "");
	}
}

void GDUtil::trimTabEnter(std::string &s1)
{
	if (s1.empty() || s1 == "" || s1.length() < 1){
		return;
	}
	
	GDUtil::replace(s1, "　", ""); // 替换全角空格
	GDUtil::replace(s1, "\t", ""); // 替换制表符
	GDUtil::replace(s1, "\n", "");
	GDUtil::replace(s1, "\r", "");
}

int GDUtil::strLen(const std::string &in){
	int length=0;
	
	for (int i = 0; i < in.length();) {
		if ((in[i] & 0x80) == 0x00)
		{//0x0xxxxxx 只占一个字节
			length+=1;
			++i;
		}
		else
		{
			if ((in[i] & 0xe0) == 0xc0)
			{//0x110xxxxx 0x10xxxxxx 占两个字节
				length += 2;
				++i;
				++i;
			}
			else
			{
				if ((in[i] & 0xf0) == 0xe0)
				{//占3个字节
					length += 2;
					++i;
					++i;
					++i;
				}
			}
		}
	}
	//CCLog("---------------%d",length);
	return length;
}

std::string GDUtil::encryptMobile(const std::string& mobile)
{
	if (mobile.empty() || mobile == ""){
		return "";
	}
	int length = mobile.length();
	if (length < 9){
		return mobile;
	}

	return mobile.substr(0, length - 8) + "****" + mobile.substr(length - 4);
}

int GDUtil::indexOf(const char *str, const char *dest){
	std::string s = str;

	int p = (int)s.find(dest);
	if (p == s.npos){
		p = -1;
	}
	return p;
}

char * GDUtil::substring(const char *str, int start, int len)
{
	register int i = 0;
	char *tmp;

	if (len<1 || start>strlen(str))
		return(NULL);

	tmp = (char*)malloc((len + 1)*sizeof(char));

	for (i = 0, str += start; i<len&&*str; i++)
		tmp[i] = *str++;

	tmp[i] = 0;

	return(tmp);
}

void GDUtil::toUpper(char* str)
{
	int len = (int)strlen(str);
	if (len < 1){
		return;
	}
	int i;
	for (i = 0; i< strlen(str); i++)
	{
		str[i] = toupper(str[i]);
	}
}

bool GDUtil::isFullUrl(const std::string &url){
	//CCLog("url=%s", url.c_str());
	// 如果url不是以http开头或者https开头
	if (GDUtil::beginWith(url, "http://") || !GDUtil::beginWith(url, "https://")){
	//	CCLog("false result");
	//if ((strncmp(url.c_str(), "http://", strlen("http://")) != 0) || (strncmp(url.c_str(), "https://", strlen("https://")) != 0)){ 
		return true;
	}
	return false;
}

bool GDUtil::beginWith(const std::string str, const std::string needle){
	if (strncmp(str.c_str(), needle.c_str(), needle.length()) == 0){
		//CCLog("str=%s,needle=%s true", str.c_str(), needle.c_str());
		return true;
	}

	//CCLog("str=%s,needle=%s false", str.c_str(), needle.c_str());
	return false;
	//return strncmp(str.c_str(), needle.c_str(), strlen(needle.c_str())) == 0;
}

bool GDUtil::endWith(const std::string str, const std::string needle){
	if (str.length() >= needle.length()) {
		return (0 == str.compare(str.length() - needle.length(), needle.length(), needle));
	}
	return false;
}

void GDUtil::getAllFilePaths(std::vector<std::string>& filePaths, std::vector<std::string>& dirPaths, const std::string& path)
{
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
    std::string p = path.at(path.length() - 1) == '/' ? path : path + "/";
    
    struct dirent *ptr;
    DIR* dir;
    dir = opendir(p.c_str());
    if(dir == NULL)return;
    while ((ptr = readdir(dir)) != NULL)
    {
        std::string file_path = p + ptr->d_name;
        
        if (ptr->d_type == DT_DIR && ptr->d_name[0] != '.')
        {
            dirPaths.push_back(file_path);
            getAllFilePaths(filePaths, dirPaths, file_path);
        }
        else
        {
            filePaths.push_back(file_path);
        }
    }
    
    closedir(dir);
#endif
}


unsigned long GDUtil::getFilePathSize(const std::string& path)
{
    unsigned long lCurFileSize = 0;
    
    std::vector<std::string> filePaths;
    std::vector<std::string> dirPaths;
    getAllFilePaths(filePaths, dirPaths, path);
    
    for (int i=0; i<filePaths.size(); i++)
    {
        FILE* fp = fopen(filePaths.at(i).c_str(), "r");
        if (fp != NULL)
        {
            fseek(fp, 0L, SEEK_END);
            lCurFileSize += ftell(fp);
            fclose(fp);
        }
    }
    
    return lCurFileSize;
}

void GDUtil::removeFilePath(const std::string& path)
{
    std::vector<std::string> filePaths;
    std::vector<std::string> dirPaths;
    getAllFilePaths(filePaths, dirPaths, path);
    
    for (std::vector<std::string>::iterator itr=filePaths.begin();
         itr!=filePaths.end();
         itr++)
    {
        remove(itr->c_str());
    }
    
    for (std::vector<std::string>::iterator itr=dirPaths.begin();
         itr!=dirPaths.end();
         itr++)
    {
        remove(itr->c_str());
    }

}

void GDUtil::removeFile(const std::string& file, bool removeImageCache){
	if (CCFileUtils::sharedFileUtils()->isFileExist(file)){
		remove(file.c_str());
	}
	
	if (removeImageCache){
		CAImageCache::sharedImageCache()->removeImageForKey(file);
	}
}

void GDUtil::saveToFile(const std::string& fileName, const std::string& data, const std::string& filePath){
	std::string imagePath = CCFileUtils::sharedFileUtils()->getWritablePath() + filePath;
	CCFileUtils::sharedFileUtils()->createDirectory(imagePath.c_str());

	imagePath = imagePath + fileName;
	if (IS_DEBUG) CCLog("保存文件到目录：%s", imagePath.c_str());
	FILE *fp = fopen(imagePath.c_str(), "wb+");
	if (fp)
	{
		fwrite(data.c_str(), sizeof(char), strlen(data.c_str()), fp);
		fclose(fp);
	}
}

void GDUtil::sendStatisticsToService(std::string type, const std::string& f1, const std::string& f2, const std::string& f3, const std::string& f4, const std::string& f5, const std::string& f6){
	std::map<string, string> key_value;
	key_value["type"] = type;
	key_value["f1"] = f1;
	key_value["f2"] = f2;
	key_value["f3"] = f3;
	key_value["f4"] = f4;
	key_value["f5"] = f5;
	key_value["f6"] = f6;

	//GDHttpUtil::getInstance()->send_get(GD_tongji_rul, key_value, NULL, NULL, false);
}

bool GDUtil::isImageInCache(const std::string& uri, const HttpGetImageType type)
{	
	if (type == HttpGetImageNoAllCache){
		return false;
	}

	string url = getFullUrl(uri);
	std::string key = MD5(url).md5();
	std::string imagePath = CCFileUtils::sharedFileUtils()->getWritablePath() + "image/" + key;

	if (type == HttpGetImageDefault){
		// 内存中查询
		if (CAImageCache::sharedImageCache()->imageForKey(imagePath) != NULL){
			return true;
		}
	}
	
	// 查询缓存目录
	
	if (CCFileUtils::sharedFileUtils()->isFileExist(imagePath)){
		return true;
	}
	
	return false;
}

bool GDUtil::isImageInMemory(const std::string& uri)
{
	string url = getFullUrl(uri);
	std::string key = MD5(url).md5();
	std::string imagePath = CCFileUtils::sharedFileUtils()->getWritablePath() + "image/" + key;
	//if (IS_DEBUG) CCLog("查询图片%s是否在缓存中图片", key.c_str());

	if (CAImageCache::sharedImageCache()->imageForKey(imagePath) != NULL){
		return true;
	}

	return false;
}

float GDUtil::getAngle(float x, float y)
{
	if (y == 0){
		if (x > 0){
			return 0;
		}
		else{
			return 180;
		}
	}
	else if (x == 0){
		if (y>0){
			return 90;
		}
		else if (y < 0){
			return 270;
		}
		else{
			return 0;
		}
	}
	float tan = atan2(y,x);
	CCLog("--------------------%f",tan);
	tan = tan * 360 / (2 * 3.1415926535898);

	return tan;
}

CCPoint GDUtil::getRotationAnglePoint(CCPoint centPoint, CCPoint srcPoint, float rotation)
{
	//  假设对图片上任意点(x,y)，绕一个坐标点(rx0,ry0)逆时针旋转a角度后的新的坐标设为(x0, y0)，有公式：
	//   x0= (x - rx0)*cos(a) - (y - ry0)*sin(a) + rx0 ;
	//   y0 = (x - rx0)*sin(a) + (y - ry0)*cos(a) + ry0;
	rotation = rotation * 3.1415926535898 / 180;
	float x0 = (srcPoint.x - centPoint.x)*cos(rotation) - (srcPoint.y - centPoint.y)*sin(rotation) + centPoint.x;
	float y0 = (srcPoint.x - centPoint.x)*sin(rotation) + (srcPoint.y - centPoint.y)*cos(rotation) + centPoint.y;
	return CCPoint(x0, y0);
}